const fs = require('fs');
const path = require('path');

function generateSidebar(paths) {
  const sidebar = {};
  
  // 确保 paths 是数组
  const dirPaths = Array.isArray(paths) ? paths : [paths];
  
  dirPaths.forEach(dirPath => {
    // 获取目录名称
    const dirName = path.basename(dirPath);
    console.log('处理目录:', dirName);

    if (fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory()) {
      sidebar[`/${dirName}/`] = [{
        title: dirName.charAt(0).toUpperCase() + dirName.slice(1),
        collapsable: false,
        children: generateChildren(dirPath, '')
      }];
    } else {
      console.warn(`警告: 目录 ${dirPath} 不存在或不是目录`);
    }
  });

  console.log('生成的 sidebar 配置:', JSON.stringify(sidebar, null, 2));
  return sidebar;
}

function generateChildren(dirPath, parentPath) {
  const children = [];
  const items = fs.readdirSync(dirPath);

  // 处理 README.md
  if (items.includes('README.md')) {
    children.push('');
  }

  // 处理子目录和文件
  items.forEach(item => {
    const fullPath = path.join(dirPath, item);
    if (fs.statSync(fullPath).isDirectory()) {
      const dirChildren = processDirectory(fullPath, `${parentPath}${item}`);
      if (dirChildren.length > 0) {
        children.push({
          title: item,
          collapsable: true,
          children: dirChildren
        });
      }
    }
  });

  return children;
}

function processDirectory(dirPath, relativePath) {
  const children = [];
  const items = fs.readdirSync(dirPath);

  // 先处理 md 文件
  items.forEach(item => {
    if (item.endsWith('.md') && item !== 'README.md') {
      const name = item.slice(0, -3);
      children.push(`${relativePath}/${name}`);
    }
  });

  // 再处理子目录
  items.forEach(item => {
    const fullPath = path.join(dirPath, item);
    if (fs.statSync(fullPath).isDirectory()) {
      const subChildren = processDirectory(fullPath, `${relativePath}/${item}`);
      if (subChildren.length > 0) {
        children.push({
          title: item,
          collapsable: true,
          children: subChildren
        });
      }
    }
  });

  return children;
}

module.exports = generateSidebar; 